<?php
/**
 * Created by PhpStorm.
 * User: cephei
 * Date: 11/28/15
 * Time: 3:41 PM
 */
namespace Plugins\Thunder;

use Core\PluginContainer;
use phpseclib\Crypt\RSA;

class Plugin_Thunder{
    private $db;
    private $cookies=[];
    private $downloader='';
    private $absPath='';
    public function __construct()
    {
        $this->db = PluginContainer::getInstance()->singletonMake('database');
        $this->loginUser();
        $this->getDevice();
    }

    public function addTask($url,$name,$savePath,$type,$callback,$callbackArgs)
    {
        $postJson = new \stdClass();
        $thunderUrl="";
        if ($type == "http") {
            $postJson->tasks = [];
            $postJson->tasks["path"] = $this->absPath . $savePath;
            $postJson->tasks["name"] = $name;
            $postJson->tasks["url"] = $url;
            $postJson->tasks["gcid"] = "";
            $postJson->tasks["cid"] = "";
            $postJson->tasks["cid"] = "";
            $postJson->tasks["filesize"] = 0;
            $postJson->tasks["ext_json"] = new \stdClass();
            $postJson->tasks["ext_json"]->autoname = 1;
            $thunderUrl = "http://homecloud.yuancheng.xunlei.com/createTask?pid=$this->downloader&v=2&ct=0";
        }else if($type=="magnet") {
            $postJson->path = $this->absPath . $savePath;
            $curl = PluginContainer::getInstance()->make('curl');
            $curl->cookies = $this->cookies;
            $curl->method="POST";
            $curl->formData = ["json"=>'{"url":"'.$url.'"}'];
            $response = $curl->sendRequest("http://homecloud.yuancheng.xunlei.com/urlResolve?pid=$this->downloader&v=2&ct=0");
            $infoJson = json_decode($response);
            if($infoJson->rtn!=0)
                return false;
            $postJson->infohash = $infoJson->infohash;
            $postJson->name = $infoJson->taskInfo->name;
            $postJson->btSub = [];
            foreach($infoJson->taskInfo->subList as $btSub){
                if(strpos($btSub->name,$name)!==false)
                    $postJson->btSub[] = (int)$btSub->id;
            }
            $thunderUrl = "http://homecloud.yuancheng.xunlei.com/createBtTask?pid=$this->downloader&v=2&ct=0";
        }
        $curl = PluginContainer::getInstance()->make('curl');
        $curl->cookies=$this->cookies;
        $curl->formData=["json"=>json_encode($postJson)];
        $curl->method = "POST";
        $response = $curl->sendRequest($thunderUrl);
        $curl->close();
        if(strpos($response,'"rtn": 0')!==false){
            $this->db->insert('plg_thunder_tasks',[
                "name"=>$name,
                "url"=>$url,
                "savpath"=>$savePath,
                "percent"=>0,
                "taskname"=> $postJson->name,
                "type"=>$type,
                "callback"=>base64_encode(json_encode($callback)),
                "callbackargs"=>base64_encode(json_encode($callbackArgs))
            ]);
            $dbTask = $this->db->first("select * from plg_thunder_tasks where taskname='$postJson->name' and thundertaskid=-1");
            return $dbTask->id;
        }
        return false;
    }

    public function removeTask($id){

    }
    public function getTaskList(){
        $curl = PluginContainer::getInstance()->make('curl');
        $curl->cookies=$this->cookies;
        $response = $curl->sendRequest("http://homecloud.yuancheng.xunlei.com/list?pid=$this->downloader&type=0&pos=0&number=40&needUrl=1&v=2&ct=0");
        $tasksJson = json_decode($response);
        $this->db->update("plg_thunder_tasks",["status"=>-1]," where status=0");
        foreach ($tasksJson->tasks as $task) {
            $dbTask=$this->db->first("select * from plg_thunder_tasks where taskname='$task->name' and status=-1");
            if($dbTask->thundertaskid==-1){
                $this->db->update("plg_thunder_tasks",["thundertaskid"=>$task->id,"percent"=>$task->progress]," where id=$dbTask->id");
            }else{
                $this->db->update("plg_thunder_tasks",["percent"=>$task->progress]," where id=$dbTask->id");
            }
        }
        $response = $curl->sendRequest("http://homecloud.yuancheng.xunlei.com/list?pid=$this->downloader&type=1&pos=0&number=40&needUrl=1&v=2&ct=0");
        $tasksJson = json_decode($response);
        foreach ($tasksJson->tasks as $task) {
            $dbTask=$this->db->first("select * from plg_thunder_tasks where taskname='$task->name' and status=-1");
            if($dbTask->thundertaskid==-1){
                $this->db->update("plg_thunder_tasks",["thundertaskid"=>$task->id,"percent"=>$task->progress,"status"=>1]," where id=$dbTask->id");
            }else{
                $this->db->update("plg_thunder_tasks",["percent"=>$task->progress,"status"=>1]," where id=$dbTask->id");
            }
        }
        $this->db->update("plg_thunder_tasks",["status"=>2]," where status=-1 and thundertaskid !=-1");

    }
    public function addVIPUser($userName,$passWord,$userCookie){

    }
    public function removeVIPUser($userId){

    }
    public function getVIPUserList(){

    }

    public function keepLive(){

    }

    public function getDevice(){
        $curl = PluginContainer::getInstance()->make('curl');
        $curl->cookies=$this->cookies;
        $response = $curl->sendRequest("http://homecloud.yuancheng.xunlei.com/listPeer?v=2");
        $downloaderList = json_decode($response);
        foreach ($downloaderList->peerList as $downloader) {
            if($downloader->online==1) {
                $this->downloader = $downloader->pid;
                if(is_array($downloader->path_list))
                    $this->absPath = $downloader->path_list[0];
                else
                    $this->absPath = $downloader->path_list;
                return;
            }
        }
        $curl->close();
    }

    public function loginUser(){
        $userInfo = $this->db->first('select * from plg_thunder_users');
        $userName = $userInfo->username;
        $userSessionId = $userInfo->usersessionid;
        $curl = PluginContainer::getInstance()->make('curl');
        $curl->header = true;
        $response = $curl->sendRequest("https://login.xunlei.com/check/?u=$userName&business_type=108&cachetime=".time()*1000);
        preg_match_all('/Set-Cookie:(.*);/iU', $response, $cookies);

        $postCookie=[];
        foreach($cookies[1] as $cookie){
            $pair = explode('=', $cookie);
            $postCookie[trim($pair[0])] = trim($pair[1]);
        }

        $post = [
            "sessionid"=>$userSessionId,
            "v" => 100,
            "cachetime" => time() * 1000
        ];
        $curl->cookies = $postCookie;
        $curl->method = "POST";
        $curl->formData = $post;
        $curl->header= true;
        $response = $curl->sendRequest("https://login.xunlei.com/sessionid/");
        preg_match_all('/Set-Cookie:(.*);/iU', $response, $cookies);
        $curl->close();

        foreach($cookies[1] as $cookie){
            $pair = explode('=', $cookie);
            $this->cookies[trim($pair[0])] = trim($pair[1]);
        }
    }
}